part of '../repository.dart';

const _kCustomCollectionFolderTypeValue = 'custom_collection_folder';

class _CustomCollectionFolderDto extends Equatable
    implements _CustomCollectionListItemDto, _CollectionFolderDto {
  const _CustomCollectionFolderDto({
    required this.id,
    required this.title,
    required this.collectionDtos,
  });

  @override
  final String id;

  @override
  final String title;

  @override
  final BuiltList<_CustomCollectionDto> collectionDtos;

  @override
  String get type => _kCustomCollectionFolderTypeValue;

  @override
  List<Object?> get props {
    return [
      id,
      title,
      collectionDtos,
    ];
  }

  @override
  CustomCollectionFolder toEntity() {
    final collections = collectionDtos.map((collectionDto) {
      return collectionDto.toEntity();
    }).toBuiltList();

    return CustomCollectionFolder(
      id: id,
      title: title,
      collections: collections,
    );
  }

  @override
  Map<String, dynamic> toJson() {
    final collectionJsons = collectionDtos.map((collectionDto) {
      return collectionDto.toJson();
    }).toList();

    return {
      _kCollectionListItemTypeKey: type,
      _kCollectionListItemIdKey: id,
      _kCustomCollectionListItemTitleKey: title,
      _kCollectionFolderCollectionsKey: collectionJsons,
    };
  }

  factory _CustomCollectionFolderDto.fromEntity(CustomCollectionFolder folder) {
    final collectionDtos = folder.collections.map((collection) {
      return _CustomCollectionDto.fromEntity(collection);
    }).toBuiltList();

    return _CustomCollectionFolderDto(
      id: folder.id,
      title: folder.title,
      collectionDtos: collectionDtos,
    );
  }

  factory _CustomCollectionFolderDto.fromJson(Map<String, dynamic> json) {
    final collectionMaps = List.castFrom<dynamic, Map>(json[_kCollectionFolderCollectionsKey]);

    final collectionDtos = collectionMaps.map((collectionMap) {
      final collectionJson = Map.castFrom<dynamic, dynamic, String, dynamic>(collectionMap);

      return _CustomCollectionDto.fromJson(collectionJson);
    }).toBuiltList();

    return _CustomCollectionFolderDto(
      id: json[_kCollectionListItemIdKey],
      title: json[_kCustomCollectionListItemTitleKey],
      collectionDtos: collectionDtos,
    );
  }
}
